﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using OauthProvider;

namespace Chat_WebServer.Controllers
{
    public class OAuthAccountController : ApiController
    {
        private static IOAuthProvider provider;

        public OAuthAccountController()
        {
            var consumerStore = new ConsumerStore();
            SimpleTokenStore tokenStore = new SimpleTokenStore();
            provider = new OAuthProvider(tokenStore,
                                   new ConsumerValidationInspector(consumerStore),
                                   new OAuth10AInspector(tokenStore));
        }

        // Dang nhap
        public Account Get()
        {
            IOAuthContext context = new OAuthContextBuilder().FromUri(HttpMethod.Get.ToString(), Request.RequestUri);
            try
            {
                provider.AccessProtectedResourceRequest(context);

                var accessToken = (MiniAccessToken)TokenUtility.GetToken(context.Token, TokenType.Access);

                string username = accessToken.UserName;
                using (var db = new AccountEntities())
                {
                    // neu chua dang nhap
                    if (AccountController.onlines.IndexOf(username) < 0)
                    {
                        var temp = db.Accounts.ToList().FirstOrDefault(a => a.Username.Trim() == username);
                        if (temp != null)
                        {
                            AccountController.onlines.Add(username);
                            return temp;
                        }
                    }
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        // Thoat ra
        public HttpStatusCode Delete()
        {
            IOAuthContext context = new OAuthContextBuilder().FromUri(HttpMethod.Get.ToString(), Request.RequestUri);
            try
            {
                provider.AccessProtectedResourceRequest(context);

                var accessToken = (MiniAccessToken)TokenUtility.GetToken(context.Token, TokenType.Access);

                string userName = accessToken.UserName;
                using (var db = new AccountEntities())
                {
                    AccountController.onlines.Remove(userName);
                    return HttpStatusCode.OK;
                }
            }
            catch (Exception ex)
            {
                return HttpStatusCode.NotFound;
            }
            return HttpStatusCode.NotFound;
        }
    }
}
